<?php

namespace App\Http\Controllers\Posts;

use App\Models\Cates;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CatesController extends Controller
{
    /** 文章分类列表 */
    public function index(Request $request)
    {
        if($request->isMethod('post')){
            $model = Cates::lists();
            return $this->data($model);
        }
        return view('posts.cates.index');
    }

    /** 编辑分类 */
    public function edit(Request $request)
    {
        $id = $request->get('id');
        $pid = $request->get('pid');

        if(empty($id)){
            $model = new Cates();
        }else{
            $model = Cates::find($id);
        }

        if($request->isMethod('post')){
            $data = $request->all();

            /** 基础验证 */
            $validator = $this->validateCates($data);
            if ($validator->fails()) {
                return $this->fail($validator->errors()->first());
            }

            $model->pid     = $data['pid'];
            $model->name    = $data['name'];
            $model->icon    = $data['icon'];
            $model->sort    = $data['sort'];

            if($model->save()){
                return $this->success('保存成功!');
            }
        }

        $cates = Cates::lists($status=false,$structure='plumb','&nbsp;&nbsp;');
        $cates = array_column($cates,'name','id');
        return view('posts.cates.edit',['cates'=>$cates,'model'=>$model,'pid'=>$pid,'id'=>$id]);
    }

    /** 排序 */
    /** 导航排序 */
    public function sort(Request $request)
    {
        $data = $request->input();
        $data['data'] = json_decode($data['data']);

        foreach($data['data'] as $key=>$item){
            $data['data'][$key] = (array)$item;
        }

        $sql = updateBatch($data['data'],'cates');

        DB::update(DB::raw($sql));
        return $this->success('保存成功');
    }


    /** 删除分类 */
    public function del(Request $request)
    {
        $id = $request->input('id');
        DB::table('cates')->where(['id'=>$id])->delete();
        DB::table('cates')->where(['pid'=>$id])->delete();
        return $this->success('删除成功');
    }

    /** 验证 */
    private function validateCates($data)
    {
        $validator = Validator::make($data, [
            'pid'       => 'required',
            'name'      => 'required',
        ], [
            'required'  => ':attribute不得为空',
        ], [
            'pid'       => '上级分类',
            'name'      => '分类名称',
        ]);
        return $validator;
    }
}
